/*
 * Copyright (c) 2025 Huawei Device Co., Ltd.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

#ifndef SMART_SERVE_SERVICES_SERVER_SCHEDULER_SCHEDULER_H
#define SMART_SERVE_SERVICES_SERVER_SCHEDULER_SCHEDULER_H

#include "assertion.h"
#include "device/manager.h"
#include "scheduler/event.h"
#include "service/config.h"
#include <atomic>
#include <condition_variable>
#include <mutex>
#include <thread>
#include <vector>

namespace OHOS {
namespace SmartServe {

class Scheduler {
public:
    Scheduler()
    {
        thread_ = std::thread([this]() { ThreadMain(); });
    }

    virtual ~Scheduler()
    {
        ASSERT(terminating_ && !thread_.joinable() && "Must call `Terminate` before destruction");
    }

    void Terminate()
    {
        {
            std::unique_lock<std::mutex> lock(mutex_);
            terminating_ = true;
        }
        cv_.notify_all();
        thread_.join();
    }

    void Schedule(std::unique_ptr<Event> event)
    {
        {
            std::unique_lock<std::mutex> lock(mutex_);
            events_.push_back(std::move(event));
        }
        cv_.notify_all();
    }
    void Init(const Config& config)
    {
        devManager_.Init(config);
    }

protected:
    std::vector<std::unique_ptr<Event>> events_;

    std::mutex mutex_;
    std::condition_variable cv_;
    std::thread thread_;

    std::atomic_bool terminating_{false};

    virtual void ThreadMain() = 0;

    DevManager devManager_;
};

} // namespace SmartServe
} // namespace OHOS

#endif // SMART_SERVE_SERVICES_SERVER_SCHEDULER_SCHEDULER_H
